package com.cmbt.dao.impl;

import com.cmbt.bean.Page;
import com.cmbt.bean.Role;
import com.cmbt.dao.api.RoleDao;
import com.cmbt.utils.DruidJdbcUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

public class RoleDaoImpl implements RoleDao {

    // commons-dbutils的操作对象
    QueryRunner qr = new QueryRunner(DruidJdbcUtils.getDataSource());

    @Override
    public List<Role> selectAllRoleList() {
        try {
            String sql = "select role_id as roleId,roleName,remark from t_role";
            List<Role> list = qr.query(sql, new BeanListHandler<>(Role.class));
            return list;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }

    @Override
    public Role selectRoleById(Integer roleId) {
        String sql = "SELECT role_id as roleId,role_name as roleName,remark FROM t_role WHERE role_id = ?";
        try {
            Role role = qr.query(sql, new BeanHandler<>(Role.class), roleId);
            return role;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }

    @Override
    public List<Role> selectRoleListByPage(Page page) {
        String sql1 = "select  role_id as roleId,role_name as roleName,remark as remark from t_role limit ?,?";  //分页查询
        int pageSize = page.getPageSize();

        // 从哪start这一条开始
        int start = (page.getCurrentPage() - 1) * pageSize;

        List<Role> roleList = null;
        try {
            roleList = qr.query(sql1, new BeanListHandler<Role>(Role.class), start,pageSize);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return roleList;


    }

    @Override
    public int selectTotalPage(int pageSize) {
        int total=0,totalPage=0;
        String sql="select count(role_id) from t_role";
        try {
            Object obj=qr.query(sql,new ScalarHandler());  //总数
            total = Integer.parseInt(String.valueOf(obj));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        totalPage=total%pageSize>0?total/pageSize+1:total/pageSize;  //总页数

        return totalPage;
    }

}
